// Captain Proto -- Protobuf Object-capability RPC
// Copyright (c) 2009 Kenton Varda, Google Inc., and contributors
// http://capnproto.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of the Captain Proto project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package capnproto;

import java.util.ArrayList;
import java.util.List;

/**
 * RPC controller implementation for Captain Proto RPCs.
 *
 * This object stores context related to a single RPC invocation.  The client
 * must create a {@code RpcContext} and pass it to the RPC method.  The
 * server receives a {@code RpcContext} when a method is called.
 *
 * In addition to the usual responsibilities of RPC controllers, this class
 * provides support for embedding service references inside RPC messages.
 * For example, to embed a service into an RPC request, call
 * {@code controller.getRequestServiceSender().send(service)}.  This returns
 * a service ID number; place the number somewhere in the request message.  On
 * the server side, the server reads the service ID number from the request
 * message, then calls
 * {@code controller.getRequestServiceReceiver().receive(id)} to obtain an
 * object representing that service, to which it can then send RPCs.
 */
public final class RpcContext {
  private final ServiceBuffer requestServices;
  private ServiceBuffer responseServices;

  /**
   * Create a new {@code RpcContext} for use on the client side.
   */
  public RpcContext() {
    requestServices = new ServiceBuffer();
  }

  RpcContext(List<Channel> receivedServices) {
    requestServices = new ServiceBuffer(receivedServices).freeze();
  }

  /**
   * Get a {@link ServiceSender} which can be used to embed service objects into
   * the RPC request.  Can only be called on the client side before the RPC has
   * started.
   */
  public ServiceSender getRequestServiceSender() {
    return requestServices;
  }

  /**
   * Get a {@link ServiceReceiver} which can be used to fetch services which
   * were embedded in the RPC request.  Can only be called on the server side.
   */
  public ServiceReceiver getRequestServiceReceiver() {
    return requestServices.freeze();
  }

  /**
   * Get a {@link ServiceSender} which can be used to embed service objects into
   * the RPC response.  Can only be called on the server side.
   */
  public synchronized ServiceSender getResponseServiceSender() {
    if (responseServices == null) {
      responseServices = new ServiceBuffer();
    }
    return responseServices;
  }

  /**
   * Get a {@link ServiceReceiver} which can be used to fetch services which
   * were embedded in the RPC response.  Can only be called on the client side
   * after the RPC has finished.
   */
  public synchronized ServiceReceiver getResponseServiceReceiver() {
    if (responseServices == null) {
      responseServices = new ServiceBuffer();
    }
    return responseServices.freeze();
  }

  synchronized void setResponseServices(List<Channel> services) {
    responseServices = new ServiceBuffer(services).freeze();
  }

  // =================================================================

  final class ServiceBuffer implements ServiceReceiver, ServiceSender {
    private final ArrayList<Channel> services =
        new ArrayList<Channel>();
    private boolean isFrozen = false;

    public ServiceBuffer() {}

    public ServiceBuffer(List<Channel> receivedServices) {
      services.addAll(receivedServices);
      isFrozen = true;
    }

    @Override
    public synchronized int send(Channel channel) {
      if (isFrozen) {
        throw new IllegalStateException("Cannot call send() after receive().");
      }
      services.add(channel);
      return services.size() - 1;
    }

    public synchronized ServiceBuffer freeze() {
      isFrozen = true;
      return this;
    }

    @Override
    public synchronized Channel receive(int id) {
      return services.get(id);
    }

    @Override
    public synchronized List<Channel> receiveAll() {
      return java.util.Collections.unmodifiableList(services);
    }
  }
}
